#!/usr/bin/env python
# _*_coding:utf-8_*_

"""
@Time :    2019/8/25 14:19
@Author:  ThinHeader
@File: views.py
@Software: PyCharm
"""
from django.contrib.auth import login
from django.http import HttpResponseRedirect
from django.urls import reverse
from django.views.generic import TemplateView
from rest_framework import response
from rest_framework.authtoken.models import Token

from account.models import User
from common.views import AuthTemplateView


class HomeView(AuthTemplateView):
    """主页面"""
    template_name = 'web/home.html'

    def get_context_data(self, **kwargs):
        kwargs['admin'] = self.request.user
        kwargs['secure'] = self.request.is_secure()
        return super(HomeView, self).get_context_data(**kwargs)


class LoginView(TemplateView):
    template_name = 'web/login.html'

    def get_context_data(self, **kwargs):
        kwargs['secure'] = self.request.is_secure()
        return super(LoginView, self).get_context_data(**kwargs)

    def get(self, request, *args, **kwargs):
        if request.user.is_authenticated():
            return HttpResponseRedirect(reverse('home'))
        return super(LoginView, self).get(request, *args, **kwargs)

    def post(self, request, *args, **kwargs):
        user = User.objects.get_or_create(request.POST)
        token, created = Token.objects.get_or_create(user=user)

        login(request, user)
        expires = 60*5
        remember = request.POST.get('remember', None)
        if remember:
            expires = 7 * 24 * 60 * 60
        response.set_cookie('userid', user.id, expires=expires)
        response.set_cookie('key', 'Token ' + token.key)
        request.session.set_expiry(0 if not expires else expires)
        return response

